package com.cqs.leetcode.dp;

import java.util.Arrays;
import java.util.function.BinaryOperator;

/**
 * @author lixiaowen
 * @create 2019-12-14
 */
public class ReverseWordinaString151 {

    public String reverseWords(String s) {
        if (s == null ) return null;

        StringBuilder sb = new StringBuilder();
        char[] chars = s.toCharArray();
        int len = s.length() - 1;
        int end = -1;//初始化
        while (len >= 0) {
            while (len >= 0 && chars[len] == ' '){
                --len;
            }
            //记录首个不为空的字符
            end = len;
            while(len>= 0 && chars[len] != ' '){
                --len;
            }
            if (len < chars.length - 1 && len + 1 <= end){
                //sb.append(Arrays.copyOfRange(chars,len + 1, end + 1));
                sb.append(chars,len+1,end-len);
                sb.append(" ");
            }
        }
        return sb.toString().trim();
    }

    public static void main(String[] args) {
        String string="a   b  all  a ";
        string="  a   b  all  a ";
        for(String a:string.split("\\s+")){
//            System.out.println(a);
        }
//        string = "";
        String reduce = Arrays.stream(string.split("\\s+")).reduce("", (s, s2) -> s2 +  " " + s).trim();
        System.out.println(reduce);

        String result = new ReverseWordinaString151().reverseWords(string);
        System.out.println(result);
    }

}
